
from django.shortcuts import render,redirect
from django.http.response import HttpResponse
import datetime
from sm_system.models import *

# Create your views here.
COOKIE_NAME = 'sm_session'

def commodity_info(request, supermarket_id=None):

    if supermarket_id:
        commoditys = CommodityInfo.objects.filter(supermarket_id=supermarket_id)
        context = {'commoditys': commoditys}
    return render(request, 'commodity/commodity.html', context)


def update(request, id):

    commodity = CommodityInfo.objects.get(id=id)
    context = {"commodity": commodity}
    return render(request, 'commodity/commodityUpdate.html', context)


def update_form(request):

    if request.POST:
        id = request.POST['id']
        commodity = CommodityInfo.objects.get(id=id)
        commodity.name = request.POST['name']
        commodity.pur_price = request.POST['pur_price']
        commodity.sell_price = request.POST['sell_price']
        commodity.save()

    return redirect('/sm_system/commodity_info/')


def add(request):
    return render(request, 'commodity/commodityAdd.html')


def add_form(request):

    if request.POST:
        supermarket_id = str(request.COOKIES.get(COOKIE_NAME))[0:4]
        commodity = CommodityInfo(
            id=request.POST['id'],
            name=request.POST['name'],
            pur_price=request.POST['pur_price'],
            sell_price=request.POST['sell_price'],
            brand_id=request.POST['brand_id'],
            type_id=request.POST['type_id'],
            supermarket_id=supermarket_id
        )

        commodity.save()

    return redirect('/sm_system/commodity_info/')


def delete(request, id):

    commodity = CommodityInfo.objects.get(id=id)
    commodity.delete()
    return redirect('/sm_system/commodity_info/')

